// 渠道协议关联管理数据
// 使用getProtocolByConvention函数动态获取各个渠道的协议信息

import { paymentChannels } from './channels'
import { protocol3Manager } from './protocol3-manager'

export interface ChannelProtocolMapping {
  channelCode: string
  channelName: string
  iconUrl?: string
  protocols: {
    provider: string        // 服务商协议ID (PROVIDER)
    directMerchant: string  // 直连商户协议ID (DIRECT_MERCHANT) 
    subMerchant: string     // 子商户协议ID (SUB_MERCHANT)
    onboarding: string      // 进件协议ID (CHANNEL_ONBOARDING)
  }
  protocolInfo: {
    provider: any           // 服务商协议详情
    directMerchant: any     // 直连商户协议详情
    subMerchant: any        // 子商户协议详情
    onboarding: any         // 进件协议详情
  }
  enabled: boolean
  createTime: string
  updateTime: string
  description?: string
}

// 根据约定动态生成渠道协议关联数据
function generateChannelProtocolMapping(channelCode: string, channelName: string, iconUrl: string): ChannelProtocolMapping {
  // 将CHANNEL_IF_WECHAT转换为CHANNEL_PROTOCOL_WECHAT用于查找
  const protocolCode = channelCode.replace('CHANNEL_IF_', 'CHANNEL_PROTOCOL_')
  
  // 使用getProtocolByConvention获取协议ID
  const providerProtocolId = protocol3Manager.getProtocolByConvention(protocolCode, 'PROVIDER')
  const directMerchantProtocolId = protocol3Manager.getProtocolByConvention(protocolCode, 'DIRECT_MERCHANT')
  const subMerchantProtocolId = protocol3Manager.getProtocolByConvention(protocolCode, 'SUB_MERCHANT')
  const onboardingProtocolId = protocol3Manager.getProtocolByConvention(protocolCode, 'ONBOARDING')
  
  // 获取协议详情
  const providerProtocol = protocol3Manager.getProtocol(providerProtocolId)
  const directMerchantProtocol = protocol3Manager.getProtocol(directMerchantProtocolId)
  const subMerchantProtocol = protocol3Manager.getProtocol(subMerchantProtocolId)
  const onboardingProtocol = protocol3Manager.getProtocol(onboardingProtocolId)
  
  return {
    channelCode,
    channelName,
    iconUrl,
    protocols: {
      provider: providerProtocolId,
      directMerchant: directMerchantProtocolId,
      subMerchant: subMerchantProtocolId,
      onboarding: onboardingProtocolId
    },
    protocolInfo: {
      provider: providerProtocol,
      directMerchant: directMerchantProtocol,
      subMerchant: subMerchantProtocol,
      onboarding: onboardingProtocol
    },
    enabled: true,
    createTime: '2024-01-01 10:00:00',
    updateTime: new Date().toLocaleString(),
    description: `${channelName}的协议配置，基于约定自动关联相应的协议`
  }
}

// 管理器类
export class ChannelProtocolMappingManager {
  private mappings: Map<string, ChannelProtocolMapping> = new Map()

  constructor() {
    this.initializeMappings()
  }

  private initializeMappings(): void {
    // 动态初始化所有渠道的协议关联
    const mappings = getAllChannelProtocolMappingsWithDefaults()
    mappings.forEach(mapping => {
      this.mappings.set(mapping.channelCode, mapping)
    })
  }

  // 获取所有渠道协议关联
  getAllMappings(): ChannelProtocolMapping[] {
    return Array.from(this.mappings.values())
  }

  // 根据渠道代码获取协议关联
  getMappingByChannel(channelCode: string): ChannelProtocolMapping | null {
    return this.mappings.get(channelCode) || null
  }

  // 获取渠道的指定模式协议
  getProtocolByChannelAndMode(channelCode: string, mode: 'provider' | 'directMerchant' | 'subMerchant' | 'onboarding'): string | null {
    const mapping = this.getMappingByChannel(channelCode)
    return mapping ? mapping.protocols[mode] || null : null
  }

  // 更新渠道协议关联
  updateMapping(channelCode: string, updates: Partial<ChannelProtocolMapping>): boolean {
    const mapping = this.mappings.get(channelCode)
    if (!mapping) return false

    const updatedMapping = {
      ...mapping,
      ...updates,
      updateTime: new Date().toLocaleString()
    }

    this.mappings.set(channelCode, updatedMapping)
    return true
  }

  // 设置渠道协议（只读模式，不支持修改）
  setChannelProtocol(_channelCode: string, _mode: 'provider' | 'directMerchant' | 'subMerchant' | 'onboarding', _protocolId: string): boolean {
    // 只读模式，不允许修改协议关联
    console.warn('渠道协议关联处于只读模式，协议由约定自动管理')
    return false
  }

  // 启用/禁用渠道
  setChannelEnabled(channelCode: string, enabled: boolean): boolean {
    const mapping = this.mappings.get(channelCode)
    if (!mapping) return false

    mapping.enabled = enabled
    mapping.updateTime = new Date().toLocaleString()
    return true
  }

  // 获取启用的渠道
  getEnabledChannels(): ChannelProtocolMapping[] {
    return this.getAllMappings().filter(mapping => mapping.enabled)
  }

  // 获取支持指定模式的渠道
  getChannelsByMode(mode: 'provider' | 'directMerchant' | 'subMerchant' | 'onboarding'): ChannelProtocolMapping[] {
    return this.getAllMappings().filter(mapping => mapping.protocols[mode])
  }
}

// 单例实例
export const channelProtocolMappingManager = new ChannelProtocolMappingManager()

// 新的只读模式，协议关联由getProtocolByConvention函数自动管理
// 不再需要手动创建默认协议配置

// 根据channels.ts动态生成完整的渠道协议关联列表
export function getAllChannelProtocolMappingsWithDefaults(): ChannelProtocolMapping[] {
  // 基于paymentChannels和约定规则生成完整列表
  const completeList = paymentChannels.map(channel => {
    return generateChannelProtocolMapping(channel.channelCode, channel.channelName, channel.iconUrl)
  })

  return completeList
}

// 导出便捷函数
export function getAllChannelProtocolMappings(): ChannelProtocolMapping[] {
  return getAllChannelProtocolMappingsWithDefaults()
}

export function getChannelProtocolMapping(channelCode: string): ChannelProtocolMapping | null {
  return channelProtocolMappingManager.getMappingByChannel(channelCode)
}

export function updateChannelProtocolMapping(channelCode: string, updates: Partial<ChannelProtocolMapping>): boolean {
  return channelProtocolMappingManager.updateMapping(channelCode, updates)
}

export function setChannelProtocol(channelCode: string, mode: 'provider' | 'directMerchant' | 'subMerchant' | 'onboarding', protocolId: string): boolean {
  return channelProtocolMappingManager.setChannelProtocol(channelCode, mode, protocolId)
}